package com.gilgamesh.mall.sdk.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;
import java.util.Map;

/**
 * 序列化组件，基于com.google.code.gson
 *
 * @author yanm
 * @date 2021/1/6 16:55
 **/
public class SerializeUtil {

    public static String toJson(Object o) {
        return new Gson().toJson(o);
    }

    public static <T> T fromJson(String json, Class<T> type) {
        if (StringUtil.isNotEmpty(json)) {
            new Gson().fromJson(json, type);
        }
        throw new CommonException("null或空串无法反序列化");
    }

    public static <T> List<T> fromJsonToList(String json,Class<T> type) {
        if (StringUtil.isNotEmpty(json)) {
            List<T> list = new Gson().fromJson(json, new TypeToken<List<T>>() {
            }.getType());
            return list;
        }
        throw new CommonException("null或空串无法反序列化");
    }

    public static <K, V> Map<K, V> fromJsonToMap(String json, Class<K> kType, Class<V> vType) {
        if (StringUtil.isNotEmpty(json)) {
            Map<K, V> map = new Gson().fromJson(json, new TypeToken<Map<K, V>>() {
            }.getType());
            return map;
        }
        throw new CommonException("null或空串无法反序列化");
    }

    public static <K, V> List<Map<K, V>> fromJsonToListMap(String json, Class<K> kType, Class<V> vType) {
        if (StringUtil.isNotEmpty(json)) {
            List<Map<K, V>> list = new Gson().fromJson(json, new TypeToken<List<Map<K, V>>>() {
            }.getType());
            return list;
        }
        throw new CommonException("null或空串无法反序列化");
    }

    /**
     * 反序列化成Map<K,list<T>
     *
     * @param json  序列化串
     * @param kType 键类型
     * @param type  list类型
     * @return
     * @author yanm
     * @date 2021/1/6 20:36
     **/
    public static <K, T> Map<K, List<T>> fromJsonToMapRightList(String json, Class<K> kType, Class<T> type) {
        if (StringUtil.isNotEmpty(json)) {
            Map<K, List<T>> map = new Gson().fromJson(json, new TypeToken<Map<K, List<T>>>() {
            }.getType());
        }
        throw new CommonException("null或空串无法反序列化");
    }


}
